package com.edu.auth;

import com.edu.commons.Constants;
import com.edu.commons.JWTUtils;
import com.edu.commons.ServiceCode;
import com.edu.commons.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.MimeHeaders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;

/**
 * @ProjectName: summer-project
 * @Titile: TokenInterceptor
 * @Author: Lucky
 * @Description: token拦截器
 */
@Component //组件注解
public class TokenInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(TokenInterceptor.class);

    /**
     * 前置拦截请求
     * @param request 请求
     * @param response 响应
     * @param handler 处理器
     * @return 布尔值，true：放行，false：拦截了
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的身份信息
        String token = request.getHeader(Constants.TOKEN_HEADER_KEY);
        //判断token是否为空
        if(token==null || token.isEmpty()){
            //从请求参数中获取token
            token = request.getParameter("token");
            if(token==null || token.isEmpty()){
                throw new ServiceException(ServiceCode.ERROR_TOKEN_IS_NULL,"token不能为空");
            }
        }
        // token不为空
        //校验token
        JWTUtils.verifyToken(token);
        return true;//放行了
    }
}
